<template>
  <div class="pages boundCard">
    <div class="pageLevel">
      <!-- 头部 -->
      <div class="content">
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
          <el-form-item>
            <el-button @click="goBack()">返回</el-button>
            <el-button type="primary" @click="submitForm('ruleForm')" style="margin-left: 30px;"> 提交</el-button>
          </el-form-item>
          <!-- 对公司 -->
          <el-form-item label="开户名称" prop="name">
            <div>{{ruleForm.name}}</div>
          </el-form-item>
          <el-form-item class="left-account" label="企业一般结算账户" prop="account" v-if="showTab==1">
            <el-input v-model="ruleForm.account" maxlength="30" placeholder="请输入" oninput="this.value=this.value.replace(/\D/g,'')" onafterpaste="this.value=this.value.replace(/\D/g,'')"></el-input>
          </el-form-item>
          <el-form-item label="开户银行" prop="bank" v-if="showTab==1">
            <el-select size="small" style="width:200px" filterable v-model="ruleForm.bank" placeholder="请先选择银行在填网点" @change="dropdown">
              <el-option v-for="item in options " :key="item.index" :label="item.bankName" :value="item.bkId"> </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="开户网点" prop="dot" v-if="showTab==1" class="Site">
            <!-- <el-autocomplete class="inline-input" :disabled="opening" v-model="ruleForm.dot" :fetch-suggestions="querySearch" placeholder="请输入内容" @select="handleSelect"></el-autocomplete> -->
            <el-select filterable remote reserve-keyword :remote-method="remoteMethod" :loading="loading" class="dots" v-model="ruleForm.dot" placeholder="请选择" :disabled="opening">
              <el-option v-for="item in restaurants" :key="item.value" :label="item.openbknm" :value="item.openbkcd"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="手机号码" prop="phone" v-if="showTab==1">
            <el-input v-model="ruleForm.phone" maxlength="11" oninput="this.value=this.value.replace(/\D/g,'')" onafterpaste="this.value=this.value.replace(/\D/g,'')" placeholder="请输入手机号码"></el-input>
          </el-form-item>
          <!-- 对个人 -->
          <el-form-item label="银行卡号" prop="account" v-if="showTab==0">
            <el-input v-model="ruleForm.account" maxlength="20" placeholder="请输入" oninput="this.value=this.value.replace(/\D/g,'')" onafterpaste="this.value=this.value.replace(/\D/g,'')"></el-input>
          </el-form-item>
          <el-form-item label="开户银行" prop="bank" v-if="showTab==0">
            <el-select size="small" style="width:200px" filterable v-model="ruleForm.bank" placeholder="请先选择银行在填网点" @change="dropdown">
              <el-option v-for="item in  optionsty" :key="item.index" :label="item.bankName" :value="item.bkId"> </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="开户网点" prop="dot" v-if="showTab==0" class="Site">
            <!-- <el-autocomplete class="inline-input" :disabled="opening" v-model="ruleForm.dot" :fetch-suggestions="querySearch" placeholder="请输入内容" @select="handleSelect"></el-autocomplete> -->
            <el-select filterable remote reserve-keyword :remote-method="remoteMethod" :loading="loading" class="dots" v-model="ruleForm.dot" placeholder="请选择" :disabled="opening">
              <el-option v-for="item in restaurants" :key="item.value" :label="item.openbknm" :value="item.openbkcd"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item class="left-phone" label="银行预留手机号" prop="phone" v-if="showTab==0">
            <el-input v-model="ruleForm.phone" maxlength="11" oninput="this.value=this.value.replace(/\D/g,'')" onafterpaste="this.value=this.value.replace(/\D/g,'')" placeholder="请输入手机号码"></el-input>
          </el-form-item>
          <el-form-item label="短信验证码" prop="verificationCode" v-if="showTab==0&& type==0">
            <el-row>
              <el-col :span="12">
                <el-input placeholder="验证码" size="small" maxlength="6" v-model="ruleForm.verificationCode" oninput="this.value=this.value.replace(/\D/g,'')" onafterpaste="this.value=this.value.replace(/\D/g,'')"></el-input>
              </el-col>
              <el-col :span="12">
                <div class="clickCode">
                  <el-button style="font-size:14px;margin-left: 50px;" v-if="codeMsg!='获取验证码'">{{countdowns+codeMsg}}</el-button>
                  <el-button @click="getCode('ruleForm')" style="font-size:14px;margin-left:50px;" v-if="codeMsg=='获取验证码'">{{countdowns+codeMsg}}</el-button>
                </div>
              </el-col>
            </el-row>
          </el-form-item>
          <el-dialog title="短信验证" :visible.sync="dialogFormVisible" width="576px" :closeOnClickModal='false' :closeOnPressEscape='false'>
            <!-- <el-form-item :label-width="formLabelWidth">
              <span>短信验证码已发送至您的手机{{phone}}</span>
            </el-form-item> -->
            <el-form-item label="短信验证码">
              <el-row>
                <el-col :span="6">
                  <el-input placeholder="验证码" size="small" maxlength="6" v-model="ruleForm.verificationCode" oninput="this.value=this.value.replace(/\D/g,'')" onafterpaste="this.value=this.value.replace(/\D/g,'')"></el-input>
                </el-col>
                <el-col :span="12">
                  <div class="clickCode">
                    <el-button style="font-size:14px;margin-left: 50px;" v-if="codeMsg!='获取验证码'">{{countdowns+codeMsg}}</el-button>
                    <el-button @click="getCode('ruleForm')" style="font-size:14px;margin-left: 50px;" v-if="codeMsg=='获取验证码'">{{countdowns+codeMsg}}</el-button>
                  </div>
                </el-col>
              </el-row>
            </el-form-item>
            <!-- <el-form-item :label-width="formLabelWidth">
              <span> 该笔充值将产生{{fee}}元手续费（从账户中扣除）</span>
            </el-form-item> -->
            <div slot="footer" class="dialog-footer">
              <el-button @click="dialogFormVisible = false">取 消</el-button>
              <el-button type="primary" @click="activateBankCard()">确 定</el-button>
            </div>
          </el-dialog>
          <!-- </el-form-item> -->
        </el-form>
      </div>
    </div>
  </div>
</template>
<script>
import { mapState } from "vuex";
import {
  bindingBankCard,
  updateBindBankCard,
  getBanks,
  getSupportBanks,
  getAccountInfo,
  getPaymentBanks,
  sendPhoneCode,
  activateBankCard
} from "@/api";
import util from "@/util";
export default {
  computed: {
    ...mapState({
      merchantId: state => state.merchantId,
      path: state => state.path
    })
  },
  data() {
    const validMobilePhone = (rule, value, callback) => {
      if (!util.validMobilePhone(value)) {
        return callback(new Error("手机号格式不正确 "));
      } else {
        callback();
      }
    };
    return {
      searchInfo: "",
      loading: false,
      type: "",
      searchInfo: "",
      restaurants: [],
      trading: "",
      options: [],
      optionsty: [],
      dotid: "",
      Information: "",
      dialogFormVisible: false,
      opening: true,
      codeDisabled: false, // 是否禁用按钮
      countdown: 120, //120秒
      countdowns: "", //验证码秒数
      timer: null, // 定时器
      codeMsg: "获取验证码", //按钮上的文字
      showTab: "",
      ruleForm: {
        name: "",
        account: "",
        bank: "",
        dot: "",
        phone: "",
        verificationCode: ""
      },
      rules: {
        name: [{ required: true, message: "请输入开户名称", trigger: "blur" }],
        account: [
          {
            required: true,
            message: "请输入银行账户",
            trigger: "blur"
          },
          { min: 4, max: 20, message: "银行卡号格式错误", trigger: "blur" }
        ],
        bank: [{ required: true, message: "请输入开户银行", trigger: "blur" }],
        dot: [{ required: true, message: "请输入开户网点", trigger: "blur" }],
        phone: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { max: 11, message: "长度在11个字符", trigger: "blur" },
          { validator: validMobilePhone, trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.showTab = util.getQuery().showTab;
    this.type = util.getQuery().type;
    let arr = this.path;
    // arr.pop();
    if (this.type == "1" || this.type == "11") {
      this.opening = false;
    }
    if (this.showTab == "1") {
      arr.push({
        label: "绑定对公提现银行卡"
      });
      this.rules.account[0].message = "请输入企业一般结算账户";
      this.rules.account[1].max = 30;
    }
    if (this.showTab == "0") {
      arr.push({
        label: "绑定个人提现银行卡"
      });
      this.rules.account[0].message = "请输入银行卡号";
      this.rules.account[1].max = 20;
    }
  },
  mounted() {
    this.getBanks(); //银行信息
    this.getSupportBanks(); //对个人信息
    this.getAccountInfo(); //账号信息
  },
  methods: {
    remoteMethod(query) {
      console.log(query);
      if (query !== "") {
        this.loading = true;
        setTimeout(() => {
          this.loading = false;
          this.searchInfo = query;
          this.getPaymentBanks(this.ruleForm.bank);
        }, 200);
      } else {
      }
    },
    routerPush(name, showTab) {
      util.routerTo(name, {
        showTab: showTab
      });
    },
    activateBankCard() {
      if (
        this.ruleForm.verificationCode == "" ||
        this.ruleForm.verificationCode == "123456"
      ) {
        //||this.ruleForm.verificationCode == "123456"
        this.$message({
          message: "验证码格式不正确",
          center: true,
          duration: "3000"
        });
        return false;
      }
      let data = {
        orgId: this.merchantId,
        type: 1,
        actiinfo: this.ruleForm.verificationCode,
        bankCardNumber: this.ruleForm.account,
        bizSerialNumber: this.trading
      };
      activateBankCard(data).then(res => {
        if (res.data.message == "成功") {
          this.$store.commit("SETISRELOADDATA", true);
          util.routerTo("/financial-center/account-center/finance-account");
        } else {
          let number = 3 - parseInt(res.data.errNum);
          this.$alert(
            res.data.message +
              ", 您还有" +
              number +
              "次输入机会，若3次错误后，则当日无法继续进行绑卡",
            {
              confirmButtonText: "确定",
              center: true,
              showClose: false,
              callback: action => {}
            }
          );
        }
      });
    },
    querySearch(queryString, cb) {
      var restaurants = this.restaurants;
      var results = queryString
        ? restaurants.filter(this.createFilter(queryString))
        : restaurants;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createFilter(queryString) {
      return restaurant => {
        return (
          restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) ===
          0
        );
      };
    },

    handleSelect(item) {
      // console.log(item);
    },
    getAccountInfo() {
      let data = {
        orgId: this.merchantId
      };
      getAccountInfo(data).then(res => {
        this.getPaymentBanks(res.data.bkId);
        this.ruleForm.name = res.data.accountName;
        this.ruleForm.account = res.data.bankCardNumber;
        this.ruleForm.bank = res.data.bkId;
        this.ruleForm.dot = res.data.openBkCd;
        console.log(this.ruleForm.dot);
        this.ruleForm.phone = res.data.phone;
        // this.ruleForm.name = res.data.accountName;
        // this.$store.commit("SETTRADING", this.ruleForm.name);
      });
    },
    dropdown(val) {
      this.opening = false;
      this.Information = val;
      this.getPaymentBanks();
    },
    getPaymentBanks(id) {
      if (id != undefined || id == "") {
        this.Information = id;
      }
      if (this.Information != "") {
        let data = {
          searchInfo: this.searchInfo,
          orgId: this.merchantId,
          bkId: this.Information
        };
        getPaymentBanks(data).then(res => {
          //默认网点
          this.loadAll = res.data.list;
          for (var i = 0; i < this.loadAll.length; i++) {
            this.loadAll[i].value = this.loadAll[i].openbknm;
            this.loadAll[i].address = this.loadAll[i].openbkcd;
          }
          this.restaurants = this.loadAll;
        });
      }
    },
    getBanks() {
      // ...............对公银行下拉
      let data = {
        orgId: this.merchantId
      };
      getBanks(data).then(res => {
        this.options = res.data.list;
      });
    },
    getSupportBanks() {
      // ...............对个人银行下拉
      let data = {
        orgId: this.merchantId
      };
      getSupportBanks(data).then(res => {
        this.optionsty = res.data.list;
        console.log(this.optionsty);
      });
    },
    //------------------------变更结算卡
    updateBindBankCard() {
      let data = {
        orgId: this.merchantId,
        bkaccAccno: this.ruleForm.account,
        bkaccAcctp: this.showTab,
        bkId: this.ruleForm.bank,
        openBkCd: this.ruleForm.dot,
        bkaccPhone: this.ruleForm.phone
      };
      updateBindBankCard(data).then(res => {
        if (res.code == 200) {
          this.$message({
            message: res.data.message,
            center: true,
            duration: "1000"
          });
          if (res.data.message == "成功") {
            //变更成功后 判断是否需要金额验证
            if (res.data.state == "4") {
              this.$store.commit("SETISRELOADDATA", true);
              console.log(res.data.state);
              this.routerPush(
                "/financial-center/account-center/finance-account/finance-verify",
                this.showTab
              );
            }
            //else if (this.showTab == "1") {
            //   this.$store.commit("SETISRELOADDATA", true);
            //   this.routerPush("account");
            // }
            else if (res.data.state == "3") {
              this.dialogFormVisible = true;
            } else if (res.data.state == "2") {
              this.$store.commit("SETISRELOADDATA", true);
              util.routerTo("/financial-center/account-center/finance-account");
            } else if (res.data.state == "1") {
              this.$store.commit("SETISRELOADDATA", true);
              util.routerTo("/financial-center/account-center/finance-account");
            }
          }
          this.trading = res.data.bizSerialNumber;
          // 验证码120秒倒计时
          if (!this.timer) {
            this.timer = setInterval(() => {
              if (this.countdown > 0 && this.countdown <= 120) {
                this.countdown--;
                if (this.countdown !== 0) {
                  this.codeMsg = "" + "重新获取";
                  this.countdowns = this.countdown + "S";
                } else {
                  clearInterval(this.timer);
                  this.codeMsg = "获取验证码";
                  this.countdowns = "";
                  this.countdown = 120;
                  this.timer = null;
                  this.codeDisabled = false;
                }
              }
            }, 1000);
          }
        } else {
          this.$message({
            message: res.data.message,
            center: true,
            duration: "3000"
          });
        }
      });
    },
    //----------------------绑结算卡
    bindingBankCards() {
      console.log(999999);
      let data = {
        orgId: this.merchantId,
        bankCardNumber: this.ruleForm.account,
        bkaccKd: this.showTab,
        bkId: this.ruleForm.bank,
        openBkCd: this.ruleForm.dot,
        bkaccPhone: this.ruleForm.phone
      };
      bindingBankCard(data).then(res => {
        if (res.code == "200") {
          this.$message({
            message: res.data.message,
            center: true,
            duration: "1000"
          });
          if (res.data.message == "成功") {
            if (res.data.state == "4") {
              this.$store.commit("SETISRELOADDATA", true);
              this.routerPush(
                "/financial-center/account-center/finance-account/finance-verify",
                this.showTab
              );
            } else if (res.data.state == "2") {
              this.$store.commit("SETISRELOADDATA", true);
              util.routerTo("/financial-center/account-center/finance-account");
            } else if (res.data.state == "1") {
              this.$store.commit("SETISRELOADDATA", true);
              util.routerTo("/financial-center/account-center/finance-account");
            }
            // else if (this.showTab == "1") {
            //   this.$store.commit("SETISRELOADDATA", true);
            //   this.routerPush("account");
            // }
          }
          this.trading = res.data.bizSerialNumber;
          // 验证码120秒倒计时
          if (!this.timer) {
            this.timer = setInterval(() => {
              if (this.countdown > 0 && this.countdown <= 120) {
                this.countdown--;
                if (this.countdown !== 0) {
                  this.codeMsg = "" + "重新获取";
                  this.countdowns = this.countdown + "S";
                } else {
                  clearInterval(this.timer);
                  this.codeMsg = "获取验证码";
                  this.countdowns = "";
                  this.countdown = 120;
                  this.timer = null;
                  this.codeDisabled = false;
                }
              }
            }, 1000);
          }
        } else {
          this.$message({
            message: res.data.message,
            center: true,
            duration: "3000"
          });
        }
      });
    },
    goBack() {
      history.back();
    },
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          if (this.showTab == 1) {
            if (this.type == "1") {
              this.updateBindBankCard(); //对公--变更
            } else if (this.type == "11") {
              this.bindingBankCards(); //对公---金额验证修改绑卡
            } else if (this.type == "0") {
              this.bindingBankCards(); //对公--绑卡
            }
          }
          if (this.showTab == 0) {
            if (this.type == "0") {
              this.activateBankCard(); // 个人--绑卡--短信验证
            } else if (this.type == "1") {
              this.getCode(formName); //个人--变更--获取短信验证
            }
          }
        } else {
          // console.log("error submit!!");
          return false;
        }
      });
    },
    checkMobile(s) {
      var length = s.length;
      if (length == 11 && /^1[3|4|5|7|8][0-9]\d{4,8}$/.test(s)) {
        return true;
      } else {
        return false;
      }
    },
    // 对个人---------------------获取验证码
    getCode(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          if (
            this.ruleForm.phone !== "" &&
            this.checkMobile(this.ruleForm.phone)
          ) {
            if (this.type == "1") {
              this.updateBindBankCard();
            } else if (this.type == "0") {
              this.bindingBankCards();
            }
          } else {
            this.$message({
              message: "请输入正确的手机号",
              center: true,
              duration: "1000"
            });
          }
        } else {
          // console.log("error submit!!");
          return false;
        }
      });
    }
  }
};
</script>
<style scoped>
.boundCard .content {
  width: 500px;
  margin-top: 30px;
  margin-left: 50px;
}
.boundCard .content .span2 {
  position: absolute;
  left: 412px;
  top: 0px;
  color: #c0c4cc;
  width: 252px;
}
</style>
<style>
.boundCard .left-account .el-form-item__label {
  width: 175px !important;
  margin-left: -77px !important;
}
.boundCard .left-phone .el-form-item__label {
  width: 175px !important;
  margin-left: -77px !important;
}
.boundCard .Site .el-autocomplete {
  display: block !important;
}
.boundCard .dots {
  width: 400px;
}
.boundCard .dots .el-input__suffix {
  display: none;
}
</style>
